// Learn cc.Class:
//  - https://docs.cocos.com/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

cc.Class({
    extends: cc.Component,
    ctor(){
        this.dmList = [];
        this.FPS = 60;
    },
    properties: {   
        //弹幕预制体
        dmItemPrefab: cc.Prefab
    },
    onLoad () {
        this.node.on('initDM', (arr)=>{
            for(let i=0; i<arr.length; i++){
                let dm = this.createDm(arr[i]);
                this.setPosition(dm)
                this.node.addChild(dm)
                this.dmList.push(dm)
            }
        })
        this.node.on('createOne', (obj)=>{
            let dm = this.createDm(obj)
            this.setPosition(dm)
            this.node.addChild(dm)
            this.dmList.push(dm)
        })
    },
    setPosition(node){
        let x = this.node.width;
        let maxY = this.node.height;
        let rndY = Math.floor(Math.random()*maxY);
        node.setPosition(cc.v2(x, -rndY));
    },
    getSpeed(){
        let sMin = 200;
        let sMax = 500;
        let rndS = Math.floor(Math.random()*(sMax - sMin)+sMin);
        return rndS;
    },
    setColor(node){
        node.getChildByName('text').color = new cc.Color(255, 255, 255, 255);
    },
    createDm(obj){
        let dm = cc.instantiate(this.dmItemPrefab);
        let textNode = dm.getChildByName('text')
        let label = textNode.getComponent(cc.Label);
        let faceSprite = dm.getChildByName('dmFace').children[0].getComponent(cc.Sprite);
        dm.speed = this.getSpeed();
        dm.isSelf = obj.isSelf;
        label.string = obj.text;
        dm.width = textNode.width + textNode.x + 20;
        dm.getComponent(cc.Layout).updateLayout()
        if(obj.isSelf){
            textNode.color = new cc.Color(255, 0, 0, 255);
        }
        if(obj.img){
            cc.assetManager.loadRemote(obj.img, (err, texture) => {
                faceSprite.spriteFrame = new cc.SpriteFrame(texture);
            });
        }
        return dm;
    },
    start () {

    },

    update (dt) {
        this.FPS = 1/dt;
        for(let i=0; i<this.dmList.length; i++){
            let s = this.dmList[i].speed;
            this.dmList[i].x -= s/this.FPS;
            if(this.dmList[i].x < -750){
                this.setPosition(this.dmList[i])
                if(this.dmList[i].isSelf){
                    this.dmList[i].isSelf = false;
                    this.setColor(this.dmList[i])
                }
            }
        }

    },
});
